//
//  OrderDetailVC.swift
//  RPay
//
//  Created by CharlieLiao on 2017/7/8.
//  Copyright © 2017年 Charlie. All rights reserved.
//

class OrderDetailVC: BaseVC, UITableViewDataSource, UITableViewDelegate, CTAPIManagerParamSource, CTAPIManagerCallBackDelegate {
    
    // MARK: - Life Cycle
    override func loadView() {
        view = tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "OrderDetailGoodsCell", bundle: nil), forCellReuseIdentifier: "CellID")
        tableView.register(UINib(nibName: "OrderDetailHeadCell", bundle: nil), forCellReuseIdentifier: "CellHeadID")
        tableView.register(UINib(nibName: "OrderDetailFootCell", bundle: nil), forCellReuseIdentifier: "CellFootID")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocalStr("订单详情")
        // Do any additional setup after loading the view.
        
        if order.status == .nonPay {
            navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(点击取消订单))
        }
    }
    
    
    // MARK: - Table View Data Source
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return order.detailList.count+2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellHeadID", for: indexPath) as! OrderDetailHeadCell
            cell.orderIDLabel.text = LocalStr("订单编号：").appending(order.orderId)
            cell.orderDateLabel.text = LocalStr("订单时间：").appending(order.orderTime)
            cell.payBtn.isHidden = order.status != .nonPay
            
            if cell.payBtn.actions(forTarget: self, forControlEvent: .touchUpInside) == nil {
                cell.payBtn.addTarget(self, action: #selector(点击支付), for: .touchUpInside)
            }
            
            return cell
        }
            
        else if indexPath.row == order.detailList.count+1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellFootID", for: indexPath) as! OrderDetailFootCell
            
            cell.totalLabel.text = String(format: LocalStr("共%@件商品 合计：RH %@"), order.totalNumbers, order.totalAmount)
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! OrderDetailGoodsCell
        let goods = order.detailList[indexPath.row-1]
        cell.nameLabel.text = goods.goodsName
        cell.countLabel.text = String(format: "x%i", goods.goodsNum)
        cell.priceLabel.text = goods.perAmount
        cell.noLabel.text = LocalStr("商品编号：").appending(goods.goodsId)
        
        return cell
    }
    
    // MARK: - Table View Delegate
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 0 {
            return 68
        }
        else if indexPath.row == order.detailList.count+1 {
            return 42
        }
        
        return 60
    }
    
    // MARK: - Api ParamSource
    
    func params(forApi manager: CTAPIBaseManager!) -> [AnyHashable : Any]!
    {
        return [kApiParamOrderId: order.orderId]
    }
    
    // MARK: - Api Call Back
    func managerCallAPIDidSuccess(_ manager: CTAPIBaseManager!) {
        hideLoading()
        if _cancelApiManager == manager {
            if didTrashOrder != nil {
                didTrashOrder!(order)
            }
            navigationController!.popViewController(animated: true)
            _cancelApiManager = nil
        }
        else if _confirmApiManager == manager {
            order.status = .didPay
            // 支付成功
            let vc = PaySucceedVC()
            vc.isBuy = true
            vc.price = order.totalAmount
            navigationController!.pushViewController(vc, animated: true)
            _confirmApiManager = nil
        }
    }
    
    func managerCallAPIDidFailed(_ manager: CTAPIBaseManager!) {
        hideLoading()
        alert(manager.errorMessage)
        _cancelApiManager = nil
        _confirmApiManager = nil
    }
    
    // MARK: - Event respond
    ///
    func 点击取消订单()
    {
        // 未支付的订单才能取消
        if order.status == .nonPay {
            showLoading()
            cancelApiManager.loadData()
        }
    }
    
    func 点击支付()
    {
        let vc = ConfirmPayVC()
        vc.money = order.totalAmount
        vc.didConfirmBtn = { [weak self] (vc) in
            self?.showLoading()
            self?.confirmApiManager.loadData()
        }
        present(vc, animated: true, completion: nil)
    }
    
    // MARK: - Get
    
    var order: OrderModel!
    var didTrashOrder: ((_ order: OrderModel) -> Void)?
    
    var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 10))
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 10))
        tableView.backgroundColor = UIColor.appBackground
        tableView.allowsSelection = false
        return tableView
    }()
    
    private var _cancelApiManager: CancelOrderApiManager?
    var cancelApiManager: CancelOrderApiManager {
        if _cancelApiManager == nil {
            _cancelApiManager = CancelOrderApiManager()
            _cancelApiManager!.delegate = self
            _cancelApiManager!.paramSource = self
        }
        return _cancelApiManager!
    }
    
    private var _confirmApiManager: ConfirmPayApiManager?
    var confirmApiManager: ConfirmPayApiManager {
        if _confirmApiManager == nil {
            _confirmApiManager = ConfirmPayApiManager()
            _confirmApiManager!.delegate = self
            _confirmApiManager!.paramSource = self
        }
        return _confirmApiManager!
    }
}
